package com.ruoyi.file.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.file.service.ISysFileService;
import com.ruoyi.system.api.domain.SysFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * 文件请求处理
 * 
 * @author ruoyi
 */
@RestController
public class SysFileController
{
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;
    static String path;
    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public R<SysFile> upload(MultipartFile file)
    {
        try
        {
            // 上传并返回访问地址
            String endPoint = "oss-cn-beijing.aliyuncs.com";
            //用户信息
            String accessKeyId = "LTAI5t7tqzcZx3HBf42g65Nm";
            String accessKeySecret = "umLj9le8EkRzJT3Tbcucvwo18Qrukn";
            //存储空间名称
            String bucketName = "1hzz";
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            //文件原名
            String fileName = file.getOriginalFilename();
            //生成随机文件名
            fileName = UUID.randomUUID().toString().replace("-", "") + fileName;
            //上传文件流
            ossClient.putObject(bucketName, fileName, inputStream);
            //关闭OSSClient。
            ossClient.shutdown();
            path="https://" + bucketName + "." + endPoint + "/" + fileName;
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(path));
            sysFile.setUrl(path);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }
}